package org.csu.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.csu.mall.common.CONSTANT;
import org.csu.mall.common.ResponseCode;
import org.csu.mall.common.UniformResponse;
import org.csu.mall.entity.Category;
import org.csu.mall.persistence.CategoryMapper;
import org.csu.mall.service.ICategoryService;
import org.csu.mall.util.DateUtil;
import org.csu.mall.util.PropertiesUtil;
import org.csu.mall.vo.CategoryVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;

@Service("categoryService")
public class ICategoryServiceImpl implements ICategoryService {

    private Logger logger = LoggerFactory.getLogger(ICategoryServiceImpl.class);

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public UniformResponse<List<CategoryVO>> getChildrenCategory(String categoryId) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", categoryId).eq("status", CONSTANT.CategoryStatus.NO_CANCEL.getCode());
        List<Category> categories = categoryMapper.selectList(queryWrapper);
        if(CollectionUtils.isEmpty(categories)){
            logger.info("查找子分类，没有对应子分类");
        }
        List<CategoryVO> categoryVOList = Lists.newArrayList();
        for(Category category: categories){
            categoryVOList.add(this.entityToVO(category));
        }
        return UniformResponse.createForSuccess(ResponseCode.SUCCESS.getDescription(), categoryVOList);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public UniformResponse<List<CategoryVO>> getAllChildrenCategory(String categoryId) {
        Set<Category> categorySet = Sets.newHashSet();
        findChildCategory(categoryId, categorySet);
        List<String> categoryIdList = Lists.newArrayList();
        if(categoryId != null){
            for(Category category: categorySet){
                categoryIdList.add(category.getCategoryId());
            }
        }
        List<CategoryVO> categoryVOList = Lists.newArrayList();
        for(String id: categoryIdList){
            Category category = categoryMapper.selectOne(
                    Wrappers.<Category>query().eq("category_id", id));
            categoryVOList.add(this.entityToVO(category));
        }

        return UniformResponse.createForSuccess(ResponseCode.SUCCESS.getDescription(), categoryVOList);
    }

    private Set<Category> findChildCategory(String categoryId, Set<Category> categorySet){
        Category category = categoryMapper.selectOne(
                Wrappers.<Category>query().eq("category_id", categoryId).eq("status", CONSTANT.CategoryStatus.NO_CANCEL.getCode()));
        if(category != null){
            categorySet.add(category);
        }
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", categoryId).eq("status", CONSTANT.CategoryStatus.NO_CANCEL.getCode());
        List<Category> categoryList = categoryMapper.selectList(queryWrapper);
        for(Category categoryItem: categoryList){
            findChildCategory(categoryItem.getCategoryId(), categorySet);
        }
        return categorySet;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public UniformResponse<String> addCategory(Category category) {
        //参数判断
        if(category == null){
            return UniformResponse.createForErrorCodeMessage(
                    ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDescription());
        }
        if(StringUtils.isBlank(category.getParentId()) || StringUtils.isBlank(category.getCategoryId())){
            return UniformResponse.createForErrorCodeMessage(
                    ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDescription());
        }
        int num = categoryMapper.selectCount(
                Wrappers.<Category>query().eq("category_id", category.getCategoryId()));
        if(num > 0){
            return UniformResponse.createForErrorCodeMessage(
                    ResponseCode.CATEGORY_EXIST.getCode(), ResponseCode.CATEGORY_EXIST.getDescription());
        }

        //功能实现
        int sortOrder = categoryMapper.selectCount(
                Wrappers.<Category>query().eq("parent_id", category.getParentId())) + 1;
        while (true){
            int row = categoryMapper.selectCount(
                    Wrappers.<Category>query().eq("parent_id", category.getParentId()).eq("sort_order", sortOrder));
            if(row == 0){
                break;
            }
            sortOrder++;
        }
        category.setCategoryId(StringUtils.upperCase(category.getCategoryId()));
        category.setParentId(StringUtils.upperCase(category.getParentId()));
        category.setStatus(CONSTANT.CategoryStatus.NO_CANCEL.getCode());
        category.setSortOrder(sortOrder);
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        int row = categoryMapper.insert(category);
        if (row > 0){
            return UniformResponse.createForSuccessMessage(ResponseCode.SUCCESS.getDescription());
        }
        return UniformResponse.createForErrorCodeMessage(ResponseCode.ERROR.getCode(), ResponseCode.ERROR.getDescription());
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public UniformResponse<String> updateCategory(Category category) {
        if(category == null){
            return UniformResponse.createForErrorCodeMessage(
                    ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDescription());
        }
        Category oldCategory = categoryMapper.selectById(category.getId());
        if(oldCategory == null){
            return UniformResponse.createForErrorCodeMessage(
                    ResponseCode.COMMODITY_NOT_EXIST.getCode(), ResponseCode.CATEGORY_NOT_EXIST.getDescription());
        }
        //更新旗下的子类
        List<Category> categoryList = this.getKids(oldCategory.getCategoryId());
        for(Category item: categoryList){
            item.setParentId(category.getCategoryId());
            item.setUpdateTime(LocalDateTime.now());
            categoryMapper.updateById(item);
        }
        //更新该商品
        //todo 更新sort——order
        category.setSortOrder(category.getId());
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.updateById(category);
        return UniformResponse.createForSuccessMessage(ResponseCode.SUCCESS.getDescription());
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public UniformResponse<String> cancelCategory(String categoryId) {
        if(StringUtils.isBlank(categoryId)){
            return UniformResponse.createForErrorCodeMessage(
                    ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDescription());
        }
        //更新该类别状态为CANCEL
        Category category = categoryMapper.selectOne(Wrappers.<Category>query().eq("category_id", categoryId));
        if(category == null){
            return UniformResponse.createForErrorCodeMessage(
                    ResponseCode.COMMODITY_NOT_EXIST.getCode(), ResponseCode.CATEGORY_NOT_EXIST.getDescription());
        }
        category.setStatus(CONSTANT.CategoryStatus.CANCEL.getCode());
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.updateById(category);

        //更新其子类的父类为该类的父类
        //todo 更新sort——order
        String parentId = category.getParentId();
        List<Category> childCategoryList = this.getKids(categoryId);
        for(Category item : childCategoryList){
            item.setParentId(parentId);
            item.setUpdateTime(LocalDateTime.now());
            categoryMapper.updateById(item);
        }
        return UniformResponse.createForSuccessMessage(ResponseCode.SUCCESS.getDescription());
    }

    private List<Category> getKids(String categoryId){
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", categoryId).eq("status", CONSTANT.CategoryStatus.NO_CANCEL.getCode());
        List<Category> categories = categoryMapper.selectList(queryWrapper);
        if(CollectionUtils.isEmpty(categories)){
            logger.info("查找子分类，没有对应子分类");
        }
        return categories;
    }

    private CategoryVO entityToVO(Category category){
        CategoryVO categoryVO = new CategoryVO();
        categoryVO.setId(category.getId());
        categoryVO.setCategoryId(category.getCategoryId());
        categoryVO.setParentId(category.getParentId());
        categoryVO.setCategoryName(category.getCategoryName());
        categoryVO.setImage(category.getImage());
        categoryVO.setStatus(category.getStatus());
        categoryVO.setSortOrder(category.getSortOrder());

        //新增属性
        categoryVO.setCreateTime(DateUtil.localDateTimeToString(category.getCreateTime()));
        categoryVO.setUpdateTime(DateUtil.localDateTimeToString(category.getUpdateTime()));
        categoryVO.setImageHost(PropertiesUtil.getProperty("image.server.url"));
        return categoryVO;
    }
}
